<template>
  <div class="puzzle-container">
    <div
      :style="
        'position:relative;overflow:hidden;padding-bottom:22px;background: #eee;width:' +
          dataWidth +
          'px;'
      "
    >
      <div
        :style="
          'position:relative;width:' +
            dataWidth +
            'px;height:' +
            dataHeight +
            'px;'
        "
      >
        <img
          id="scream"
          ref="scream"
          :src="imgRandom"
          :style="'width:' + dataWidth + 'px;height:' + dataHeight + 'px;'"
        />
        <canvas
          id="puzzle-box"
          ref="puzzleBox"
          :width="dataWidth"
          :height="dataHeight"
        ></canvas>
      </div>
      <div
        class="puzzle-lost-box"
        :style="
          'left:' +
            left_Num +
            'px;width:' +
            dataWidth +
            'px;height:' +
            dataHeight +
            'px;'
        "
      >
        <canvas
          id="puzzle-shadow"
          ref="puzzleShadow"
          :width="dataWidth"
          :height="dataHeight"
        ></canvas>
        <canvas
          id="puzzle-lost"
          ref="puzzleLost"
          :width="dataWidth"
          :height="dataHeight"
        ></canvas>
      </div>
      <p class="tips_p" v-if="!displayTips">欢迎使用拼图验证，以防刷数据</p>
      <p
        :class="'ver-tips' + (displayTips ? ' slider-tips' : '')"
        ref="verTips"
      >
        <template v-if="verification">
          <p class="tips_success">
            <i style="background-position:-4px -1207px;"></i>
            <span style="color:#fff;">拼图验证成功：</span>
            <span>欢迎进入后台管理系统</span>
          </p>
        </template>
        <template v-if="!verification">
          <p class="tips_danger">
            <i style="background-position:-4px -1229px;"></i>
            <span style="color:red;">验证失败：</span>
            <span style="margin-left:4px;">拖动滑块将悬浮图像正确合并</span>
          </p>
        </template>
      </p>
    </div>

    <div class="slider-container" :style="'width:' + dataWidth + 'px;'">
      <div class="slider-bar">
        <span>请按住滑块拖动</span>
      </div>
      <div
        class="slider-btn"
        ref="sliderBtn"
        @mousedown="startMove"
        @touchstart="startMove"
      ></div>
    </div>
    <div class="refresh" @click="refreshImg">
      <el-tooltip
        class="item"
        effect="dark"
        content="刷新验证"
        placement="right"
      >
        <i class="el-icon-refresh"></i>
      </el-tooltip>
    </div>
    <div class="close" @click="closeVerificationBox">
      <i class="el-icon-close"></i>
    </div>
    <!-- <div class="drag_fo">由菜东家提供技术支持</div> -->
  </div>
</template>

<script>
export default {
  name: "puzzleVerification",
  data() {
    return {
      show: true,
      moveStart: "",
      displayTips: false,
      verification: false,
      randomX: null,
      randomY: null,
      imgRandom: "",
      left_Num: 0,
      dataWidth: null,
      dataHeight: null,
      puzzleSize: null, // 滑块的大小
      deviationValue: null,
      radius: null,
      padding: null
    };
  },
  props: {
    // 画布图片的尺寸
    width: {
      type: [String, Number],
      default: 260
    },
    height: {
      type: [String, Number],
      default: 120
    },
    // 图集
    puzzleImgList: {
      type: Array,
      default: () => [
        "../../assets/images/thumbnail-img02.jpg",
        "../../assets/images/thumbnail-img03.jpg",
        "../../assets/images/timg.jpg"
      ]
    },
    // 滑块的大小
    blockSize: {
      type: [String, Number],
      default: 40
    },
    // 误差
    deviation: {
      type: [String, Number],
      default: 4
    },
    // 滑块的圆角大小
    blockRadius: {
      type: [String, Number],
      default: 4
    },
    // 滑块随机出现的范围
    wraperPadding: {
      type: [String, Number],
      default: 20
    },
    // 滑块形状 square  puzzle
    blockType: {
      type: String,
      default: "square"
    },
    // 成功的回调
    onSuccess: {
      type: Function,
      default: () => {
        // console.log("成功");
      }
    },
    // 失败的回调
    onError: {
      type: Function,
      default: () => {
        // console.log("失败");
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCanvas();
    });
  },
  created() {
    // 随机显示一张图片
    let imgRandomIndex = Math.round(
      Math.random() * (this.puzzleImgList.length - 1)
    );
    this.imgRandom = this.puzzleImgList[imgRandomIndex];

    this.puzzleSize = Number(this.blockSize);
    this.deviationValue = Number(this.deviation);
    this.radius = Number(this.blockRadius);
    this.dataWidth = Number(this.width);
    this.dataHeight = Number(this.height);
    this.padding = Number(this.wraperPadding);
  },
  methods: {
    /* 关闭验证 */
    closeVerificationBox() {
      this.$emit("close");
    },
    /* 刷新 */
    refreshImg() {
      let imgRandomIndex = Math.round(
        Math.random() * (this.puzzleImgList.length - 1)
      );
      this.imgRandom = this.puzzleImgList[imgRandomIndex];
      this.showslider();
    },
    /* 画布初始化 */
    initCanvas() {
      this.clearCanvas();
      let w = this.dataWidth;
      let h = this.dataHeight;
      let PL_Size = this.puzzleSize;
      let padding = 50;
      let MinN_X = padding + PL_Size;
      let MaxN_X = w - padding - PL_Size - PL_Size / 6;
      let MaxN_Y = padding;
      let MinN_Y = h - padding - PL_Size - PL_Size / 6;
      this.randomX = Math.round(Math.random() * (MaxN_X - PL_Size) + MinN_X);
      this.randomY = Math.round(Math.random() * MaxN_Y + MinN_Y);
      let X = this.randomX;
      let Y = this.randomY;
      this.left_Num = -X + 10;
      let d = PL_Size / 3;
      let radius = Number(this.radius);

      let c = this.$refs.puzzleBox;
      let c_l = this.$refs.puzzleLost;
      let c_s = this.$refs.puzzleShadow;
      let ctx = c.getContext("2d");
      let ctx_l = c_l.getContext("2d");
      let ctx_s = c_s.getContext("2d");
      ctx.globalCompositeOperation = "xor";
      ctx.shadowBlur = 10;
      ctx.shadowColor = "#fff";
      ctx.shadowOffsetX = 3;
      ctx.shadowOffsetY = 3;
      ctx.fillStyle = "rgba(0,0,0,0.7)";
      ctx.beginPath();
      ctx.lineWidth = "1";
      ctx.strokeStyle = "rgba(0,0,0,0)";
      if (this.blockType === "square") {
        ctx.arc(X + radius, Y + radius, radius, Math.PI, (Math.PI * 3) / 2);
        ctx.lineTo(PL_Size - radius + X, Y);
        ctx.arc(
          PL_Size - radius + X,
          radius + Y,
          radius,
          (Math.PI * 3) / 2,
          Math.PI * 2
        );
        ctx.lineTo(PL_Size + X, PL_Size + Y - radius);
        ctx.arc(
          PL_Size - radius + X,
          PL_Size - radius + Y,
          radius,
          0,
          (Math.PI * 1) / 2
        );
        ctx.lineTo(radius + X, PL_Size + Y);
        ctx.arc(
          radius + X,
          PL_Size - radius + Y,
          radius,
          (Math.PI * 1) / 2,
          Math.PI
        );
      } else {
        ctx.moveTo(X, Y);
        ctx.lineTo(X + d, Y);
        ctx.bezierCurveTo(X + d, Y - d, X + 2 * d, Y - d, X + 2 * d, Y);
        ctx.lineTo(X + 3 * d, Y);
        ctx.lineTo(X + 3 * d, Y + d);
        ctx.bezierCurveTo(
          X + 2 * d,
          Y + d,
          X + 2 * d,
          Y + 2 * d,
          X + 3 * d,
          Y + 2 * d
        );
        ctx.lineTo(X + 3 * d, Y + 3 * d);
        ctx.lineTo(X, Y + 3 * d);
      }
      ctx.closePath();
      ctx.stroke();
      ctx.fill();

      let img = new Image();
      img.src = this.imgRandom;

      img.onload = function() {
        ctx_l.drawImage(img, 0, 0, w, h);
      };
      ctx_l.beginPath();
      ctx_l.strokeStyle = "rgba(0,0,0,0)";
      if (this.blockType === "square") {
        ctx_l.arc(X + radius, Y + radius, radius, Math.PI, (Math.PI * 3) / 2);
        ctx_l.lineTo(PL_Size - radius + X, Y);
        ctx_l.arc(
          PL_Size - radius + X,
          radius + Y,
          radius,
          (Math.PI * 3) / 2,
          Math.PI * 2
        );
        ctx_l.lineTo(PL_Size + X, PL_Size + Y - radius);
        ctx_l.arc(
          PL_Size - radius + X,
          PL_Size - radius + Y,
          radius,
          0,
          (Math.PI * 1) / 2
        );
        ctx_l.lineTo(radius + X, PL_Size + Y);
        ctx_l.arc(
          radius + X,
          PL_Size - radius + Y,
          radius,
          (Math.PI * 1) / 2,
          Math.PI
        );
      } else {
        ctx_l.moveTo(X, Y);
        ctx_l.lineTo(X + d, Y);
        ctx_l.bezierCurveTo(X + d, Y - d, X + 2 * d, Y - d, X + 2 * d, Y);
        ctx_l.lineTo(X + 3 * d, Y);
        ctx_l.lineTo(X + 3 * d, Y + d);
        ctx_l.bezierCurveTo(
          X + 2 * d,
          Y + d,
          X + 2 * d,
          Y + 2 * d,
          X + 3 * d,
          Y + 2 * d
        );
        ctx_l.lineTo(X + 3 * d, Y + 3 * d);
        ctx_l.lineTo(X, Y + 3 * d);
      }
      ctx_l.closePath();
      ctx_l.stroke();
      ctx_l.shadowBlur = 10;
      ctx_l.shadowColor = "black";
      ctx_l.clip();
      ctx_s.beginPath();
      ctx_s.lineWidth = "1";
      ctx_s.strokeStyle = "rgba(0,0,0,0)";
      if (this.blockType === "square") {
        ctx_s.arc(X + radius, Y + radius, radius, Math.PI, (Math.PI * 3) / 2);
        ctx_s.lineTo(PL_Size - radius + X, Y);
        ctx_s.arc(
          PL_Size - radius + X,
          radius + Y,
          radius,
          (Math.PI * 3) / 2,
          Math.PI * 2
        );
        ctx_s.lineTo(PL_Size + X, PL_Size + Y - radius);
        ctx_s.arc(
          PL_Size - radius + X,
          PL_Size - radius + Y,
          radius,
          0,
          (Math.PI * 1) / 2
        );
        ctx_s.lineTo(radius + X, PL_Size + Y);
        ctx_s.arc(
          radius + X,
          PL_Size - radius + Y,
          radius,
          (Math.PI * 1) / 2,
          Math.PI
        );
      } else {
        ctx_s.moveTo(X, Y);
        ctx_s.lineTo(X + d, Y);
        ctx_s.bezierCurveTo(X + d, Y - d, X + 2 * d, Y - d, X + 2 * d, Y);
        ctx_s.lineTo(X + 3 * d, Y);
        ctx_s.lineTo(X + 3 * d, Y + d);
        ctx_s.bezierCurveTo(
          X + 2 * d,
          Y + d,
          X + 2 * d,
          Y + 2 * d,
          X + 3 * d,
          Y + 2 * d
        );
        ctx_s.lineTo(X + 3 * d, Y + 3 * d);
        ctx_s.lineTo(X, Y + 3 * d);
      }
      ctx_s.closePath();
      ctx_s.stroke();
      ctx_s.shadowBlur = 20;
      ctx_s.shadowColor = "black";
      ctx_s.fill();
    },
    /* 通过重置画布尺寸清空画布，这种方式更彻底 */
    clearCanvas() {
      let c = this.$refs.puzzleBox;
      let c_l = this.$refs.puzzleLost;
      let c_s = this.$refs.puzzleShadow;
      c.setAttribute("height", c.getAttribute("height"));
      c_l.setAttribute("height", c.getAttribute("height"));
      c_s.setAttribute("height", c.getAttribute("height"));
    },
    /* 按住滑块后初始化移动监听，记录初始位置 */
    startMove(e) {
      // console.log(e);
      e = e || window.event;
      this.$refs.sliderBtn.style.backgroundPosition = "0 -216px";
      this.moveStart = e.pageX || e.touches[0].pageX;
      // this.moveStart = e.pageX;
      this.addMouseMoveListener();
    },
    /* 滑块移动 */
    moving(e) {
      let self = this;
      e = e || window.event;
      let moveX = e.pageX || e.touches[0].pageX;
      let d = moveX - self.moveStart;
      let w = self.dataWidth;
      let PL_Size = this.puzzleSize;
      let padding = this.padding;
      if (self.moveStart === "") {
        return "";
      }
      if (d < 0 || d > w - padding - PL_Size) {
        return "";
      }
      self.show = false;
      self.$refs.sliderBtn.style.left = d + "px";
      self.$refs.sliderBtn.style.transition = "inherit";
      self.$refs.puzzleLost.style.left = d + "px";
      self.$refs.puzzleLost.style.transition = "inherit";
      self.$refs.puzzleShadow.style.left = d + "px";
      self.$refs.puzzleShadow.style.transition = "inherit";
    },
    /* 移动结束，验证并回调 */
    moveEnd(e) {
      let self = this;
      e = e || window.event;
      let moveEnd_X = (e.pageX || e.changedTouches[0].pageX) - self.moveStart;
      let ver_Num = self.randomX - 10;
      let deviationValue = this.deviationValue;
      let Min_left = ver_Num - deviationValue;
      let Max_left = ver_Num + deviationValue;
      if (self.moveStart !== "") {
        if (Max_left > moveEnd_X && moveEnd_X > Min_left) {
          self.displayTips = true;
          self.verification = true;
          setTimeout(function() {
            // self.displayTips = false;
            // self.initCanvas();
            /* 成功的回调函数 */
            self.onSuccess();
          }, 500);
        } else {
          self.showslider(true);
        }
      }

      self.moveStart = "";
    },
    showslider(type) {
      let self = this;
      if (
        typeof self.$refs.sliderBtn !== "undefined" &&
        typeof self.$refs.puzzleLost !== "undefined" &&
        typeof self.$refs.puzzleShadow !== "undefined"
      ) {
        setTimeout(function() {
          self.$refs.sliderBtn.style.left = 0;
          self.$refs.sliderBtn.style.transition = "left 0.5s";
          self.$refs.puzzleLost.style.left = 0;
          self.$refs.puzzleLost.style.transition = "left 0.5s";
          self.$refs.puzzleShadow.style.left = 0;
          self.$refs.puzzleShadow.style.transition = "left 0.5s";
        }, 400);
        self.$refs.sliderBtn.style.backgroundPosition = "0 -84px";
      }
      if (type) {
        self.displayTips = true;
        self.verification = false;
      }
      setTimeout(function() {
        if (type) {
          self.displayTips = false;
        }
        self.displayTips = false;
        self.show = true;
        self.initCanvas();
        /* 失败的回调函数 */
        self.onError();
      }, 800);
    },
    /* 全局绑定滑块移动与滑动结束，移动过程中鼠标可在页面任何位置 */
    addMouseMoveListener() {
      let self = this;
      document.addEventListener("mousemove", self.moving);
      document.addEventListener("touchmove", self.moving);
      document.addEventListener("mouseup", self.moveEnd);
      document.addEventListener("touchend", self.moveEnd);
    }
  }
};
</script>

<style scoped>
.close {
  position: absolute;
  top: -30px;
  font-size: 32px;
  color: #fff;
  font-weight: bold;
  right: -40px;
}
.close:hover {
  cursor: pointer;
}
.drag_fo {
  text-align: center;
  font-size: 14px;
  color: #c1c1c1;
}
.refresh {
  cursor: pointer;
  font-size: 20px;
  color: #555;
  margin-top: 30px;
  padding-top: 15px;
  margin-bottom: 20px;
  text-align: center;
  border-top: 1px solid #ebebeb;
}

.slider-btn {
  position: absolute;
  width: 44px;
  height: 44px;
  left: 0;
  top: -7px;
  z-index: 12;
  cursor: pointer;
  background-image: url("../../assets/images/sprite.3.2.0.png");
  background-position: 0 -84px;
  transition: inherit;
}
.tips_p {
  position: absolute;
  left: 0;
  line-height: 22px;
  font-size: 12px;
  width: 100%;
  margin: 0;
  text-align: center;
}
.ver-tips {
  position: absolute;
  left: 0;
  bottom: -33px;
  background: rgba(255, 255, 255, 0.9);
  height: 24px;
  line-height: 24px;
  font-size: 12px;
  width: 100%;
  margin: 0;
  text-align: center;
  transition: all 0.4s;
}

.ver-tips .tips_success {
  background: #03a98e;
}
.ver-tips .tips_success span {
  color: #fff;
}
.ver-tips .tips_danger {
  background: #ffb9b9;
}
.ver-tips .tips_danger span {
  color: red;
}

.slider-tips {
  bottom: 0;
}

.ver-tips i {
  display: inline-block;
  width: 22px;
  height: 22px;
  vertical-align: -2px;
  background-image: url("../../assets/images/sprite.3.2.0.png");
  background-position: -4px -1229px;
}

.ver-tips span {
  display: inline-block;
  vertical-align: top;
  line-height: 24px;
  color: #455;
}

.active-tips {
  display: block;
}

.hidden {
  display: none;
}

.puzzle-container {
  position: relative;
  display: inline-block;
  padding: 10px;
  border: 1px solid #ddd;
  background: #ffffff;
}

.slider-container {
  position: relative;
  margin: 20px auto 0;
  background: rgb(235, 235, 235);
  border-radius: 1000px;
  text-align: center;
  --textColor: #333;
  --width: 150px;
  --pwidth: -150px;
  height: 30px;
}

.slider-bar {
  height: 30px;
  position: absolute;
  width: 100%;
  top: 7px;
  color: #333;
  font-size: 14px;
  -moz-user-select: none;
  -webkit-user-select: none;
  user-select: none;
  -o-user-select: none;
  -ms-user-select: none;
  background: -webkit-gradient(
    linear,
    left top,
    right top,
    color-stop(0, var(--textColor)),
    color-stop(0.4, var(--textColor)),
    color-stop(0.5, #fff),
    color-stop(0.6, var(--textColor)),
    color-stop(1, var(--textColor))
  );
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  -webkit-text-size-adjust: none;
  animation: slidetounlock 3s infinite;
}

.slider-bar * {
  -webkit-text-fill-color: var(--textColor);
}

#puzzle-box {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 22;
}

#puzzle-shadow {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 22;
}

#puzzle-lost {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 33;
}

.puzzle-lost-box {
  position: absolute;
  width: 260px;
  height: 116px;
  left: 0;
  top: 0;
  z-index: 111;
}

@-webkit-keyframes slidetounlock {
  0% {
    background-position: var(--pwidth) 0;
  }
  100% {
    background-position: var(--width) 0;
  }
}
@-webkit-keyframes slidetounlock2 {
  0% {
    background-position: var(--pwidth) 0;
  }
  100% {
    background-position: var(--pwidth) 0;
  }
}
</style>
